package gcosc.fun.hly.fastsso.filter;



import gcosc.fun.hly.fastsso.annotation.Ignore;
import gcosc.fun.hly.fastsso.domain.Vo.LoginUser;
import gcosc.fun.hly.fastsso.result.Code;
import gcosc.fun.hly.fastsso.utils.LoginUserLocal;
import gcosc.fun.hly.fastsso.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IPHandlerInterceptor implements HandlerInterceptor {

    private final TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) throws Exception {

        Ignore methodAnnotation = null;

        if (object instanceof HandlerMethod){
            HandlerMethod h = (HandlerMethod)object;
            methodAnnotation = h.getMethod().getAnnotation(Ignore.class);
        }else {
            return true;
        }

        if (methodAnnotation != null){
            return true;
        }

        String authorization = httpServletRequest.getHeader("Authorization");
        if (null == authorization || "".equals(authorization) || authorization.split(" ").length == 1) {
            Code.TOKEN_ERR("请先登录！");
        }

        String token = authorization.split(" ")[1];

        LoginUser loginUser = tokenUtil.parseToken(token);

        if (loginUser == null){
            Code.TOKEN_ERR("登陆已过期，请重新登陆");
        }

        LoginUserLocal.set(loginUser);

        return true;
    }
}
